package net.wanho.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.common.UserConstant;
import net.wanho.dto.AssignRoleDTO;
import net.wanho.dto.UserInfoDTO;
import net.wanho.dto.UserUpdDTO;
import net.wanho.exception.UserException;
import net.wanho.mapper.AuthInfoMapper;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.mapper.UserRoleMapper;
import net.wanho.po.AuthInfo;
import net.wanho.po.UserInfo;
import net.wanho.po.UserRole;
import net.wanho.service.UserInfoService;
import net.wanho.vo.PageInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 32033
 * @description 针对表【user_info(用户表)】的数据库操作Service实现
 * @createDate 2025-01-11 17:01:23
 */
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    //    private final StringRedisTemplate redisTemplate;
    private final AuthInfoMapper authInfoMapper;
    private final UserInfoMapper userInfoMapper;
    private final UserRoleMapper userRoleMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<AuthInfo> findAuthList() {
        // 获取用户id
        Integer userId = (Integer) redisTemplate.opsForValue().get("token");


        List<AuthInfo> menus = (List<AuthInfo>) redisTemplate.opsForValue().get(UserConstant.MENU_PREFIX + userId);
        if (!CollectionUtils.isEmpty(menus)) {
            return menus;
        }

        //获取当前用户所有权限
        List<AuthInfo> authInfo = authInfoMapper.selectByUserId(userId);
//        List<AuthInfo> menus;
        menus = Optional.ofNullable(authInfo).orElse(new ArrayList<>()).stream()
                .filter(item -> item.getParentId() == 0)
                .map(item -> {
                    findChildren(item, authInfo);
                    return item;
                }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(UserConstant.MENU_PREFIX + userId, menus, UserConstant.MENU_EXPIRE, UserConstant.MENU_EXPIRE_UNIT);
//        System.out.println("menus" + menus + "---------------------------");
//        System.out.println("authInfo" + authInfo + "---------------------------");
//        System.out.println("userId" + userId + "---------------------------");
        return menus;
    }

    private void findChildren(AuthInfo item, List<AuthInfo> authInfos) {
        List<AuthInfo> children = authInfos.stream()
                .filter(subItem -> subItem.getParentId().equals(item.getAuthId()))
                .map(subItem -> {
                    findChildren(subItem, authInfos);
                    return subItem;
                }).collect(Collectors.toList());
        item.setChildAuth(children);
    }

    @Override
    public PageInfo<UserInfo> listPage(Integer pageNum, Integer pageSize, UserInfoDTO userInfoDTO) {
        Page<UserInfo> page = new Page<>(pageNum, pageSize);

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.like(!ObjectUtils.isEmpty(userInfoDTO.getUserCode()), "i.user_code", userInfoDTO.getUserCode());
        wrapper.eq(!ObjectUtils.isEmpty(userInfoDTO.getRoleId()), "r.role_id", userInfoDTO.getRoleId());
        wrapper.eq(!ObjectUtils.isEmpty(userInfoDTO.getUserState()), "i.user_state", userInfoDTO.getUserState());
        // 自定义Wraper时，不会自动添加逻辑删除条件isDelete
        wrapper.eq("i.is_delete", 0);
        wrapper.orderByAsc("i.user_id");

//        Page<UserInfo> userInfoPage = this.baseMapper.selectByPage(page, wrapper);
        this.baseMapper.selectByPage(page, wrapper);

        // 封装分页信息
        PageInfo<UserInfo> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page.getCurrent());
        pageInfo.setPageSize(page.getSize());
        pageInfo.setTotalNum(page.getTotal());
        pageInfo.setPageCount(page.getPages());
        pageInfo.setLimitIndex(page.offset());
        pageInfo.setResultList(page.getRecords());

        // 获取创建人

        return pageInfo;
    }

    @Override
    public void addUser(UserInfo userInfo) {
        UserInfo user = userInfoMapper.selectByUserName(userInfo.getUserName());
        if (user != null) {
            throw new UserException("用户名已存在");
        }
        // 密码加密
        userInfo.setUserPwd(SecureUtil.md5(userInfo.getUserPwd()));
        // 默认状态
        userInfo.setUserState(UserConstant.USER_STATE);
        // 默认删除状态
        userInfo.setIsDelete(UserConstant.USER_DELETE_STATE);
        // 创建时间
        userInfo.setCreateTime(new Date());
        // 创建人id
        userInfo.setCreateBy(Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("token")).toString()));
        // 默认用户类型
        userInfo.setUserType(UserConstant.USER_TYPE);
        // 插入数据库
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void updateStateById(UserInfo userInfo) {
        UserInfo user = userInfoMapper.selectById(userInfo.getUserId());
        // 判断用户是否存在
        if (user == null) {
            throw new UserException("用户不存在");
        }
        // 修改状态
        user.setUserState(userInfo.getUserState());
        userInfoMapper.updateById(user);
    }

    @Override
    public void updateByUserId(UserUpdDTO userUpdDTO) {
        UserInfo user = userInfoMapper.selectById(userUpdDTO.getUserId());
        if (user == null) {
            throw new UserException("用户不存在");
        }

        user.setUserName(userUpdDTO.getUserName());
        user.setUserCode(userUpdDTO.getUserCode());
        user.setUpdateTime(new Date());
        user.setUpdateBy(Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get("token")).toString()));
        userInfoMapper.updateById(user);
    }

    @Override
    public void removeByUserId(Integer id) {
        UserInfo user = userInfoMapper.selectById(id);
        if (user == null) {
            throw new UserException("用户不存在");
        }
        // 删除 修改状态
        user.setIsDelete(UserConstant.USER_DELETE_STATE_DELETE);
        userInfoMapper.updateById(user);
    }

    @Override
    public void removeByUserIds(List<Integer> ids) {
        userInfoMapper.deleteBatch(ids);
    }

    @Override
    public void updatePwd(Integer id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (userInfo == null) {
            throw new UserException("用户不存在");
        }
        // 设置默认密码加密
        userInfo.setUserPwd(SecureUtil.md5(UserConstant.USER_PWD));
        // 修改密码
        userInfoMapper.updateById(userInfo);
    }


    @Override
    public void saveAssignRole(AssignRoleDTO assignRole) {
        UserInfo user = userInfoMapper.selectById(assignRole.getUserId());
        if (user == null) {
            throw new UserException("用户不存在");
        }

        String roleCheckList = assignRole.getRoleCheckList();
        String[] split = roleCheckList.split(",");
        Integer userId = assignRole.getUserId();
        Arrays.stream(split).forEach(item -> {
            UserRole userRole = new UserRole();
            Integer roleId = userRoleMapper.selectIdsByRoleName(item);
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            userRoleMapper.insert(userRole);
        });

    }

    @Override
    public List<Integer> getUserAuthList(Integer userId) {
        return userInfoMapper.findUserAuthList(userId);
    }


}






